#!/usr/bin/env python
# Copyright(c) 2009 GHCM Ltd. All rights reserved.

from mahbo.information import DB

import MySQLdb


class connectTemplate(object):
    
    def __init__(self,mainDBname):
        self.mainDBname = mainDBname
        self.connect()
    
    def connect(self):
        self.conn   = MySQLdb.connect(host = DB.database.host,user = DB.database.user,passwd = DB.database.pwd)
        self.cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)
        self.cursor.execute('SET autocommit = 1')
        self.setMainDatabase()
        self.initiateDB()
        
    def query(self, sql):
        try:
            self.cursor.execute(sql)
        except (MySQLdb.OperationalError,):
            #Incase lose connection, reconnect
            self.connect()
            self.cursor.execute(sql)
    
    def setMainDatabase(self):
        try:
            self.query('use %s' % self.mainDBname)
        except MySQLdb.OperationalError: 
            #self.mainDBname database does not exist
            self.query('create database %s' % self.mainDBname)
            self.query('use %s' % self.mainDBname)
            
    def initiateDB(self):
        pass #Reimplemented at inherited class
    
    def DisconnectDB(self):
        try:
            self.cursor.close()
            self.conn.close()
        except (MySQLdb.OperationalError):
            #In case connection already loss
            pass
            
